﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrmField.Plugins
{
    public class ServiceAppointmentManager
    {
        /// <summary>
        /// Retrieve users involved in current service appointment
        /// </summary>
        /// <param name="servicedAppointmentId"></param>
        /// <param name="service"></param>
        /// <returns></returns>
        public static List<Guid> RetrieveUsersInServiceAppointment(Guid servicedAppointmentId, IOrganizationService service)
        {
            Entity serviceApp = service.Retrieve("serviceappointment", servicedAppointmentId, new ColumnSet(new string[] { "ownerid", "resources" }));

            List<Guid> users = new List<Guid>();
            users.Add(((EntityReference)serviceApp["ownerid"]).Id);

            List<Guid> activityParties = new List<Guid>();
            foreach (Entity resource in ((EntityCollection)serviceApp["resources"]).Entities)
                activityParties.Add(resource.Id);

            QueryExpression query = new QueryExpression("activityparty");
            query.ColumnSet = new ColumnSet(new string[] { "partyid" });
            query.Criteria.AddCondition(new ConditionExpression("activitypartyid", ConditionOperator.In, activityParties.ToArray()));

            EntityCollection usersFromResources = service.RetrieveMultiple(query);
            foreach (Entity user in usersFromResources.Entities)
                users.Add(user.Id);

            return users;
        }
    }
}
